<template>
	<el-dialog title="新增账号" :visible.sync="showDialog" :before-close="cancel">
		<el-form :model="addUserData.submitProp" label-width="100px" ref="formRef">
			<el-form-item label="用户名" :rules="addUserData.userNameRules" prop="userName">
				<el-input v-model="addUserData.submitProp.userName" placeholder="请输入用户名" minlength="3" maxlength="16"></el-input>
			</el-form-item>
			<el-form-item label="角色" :rules="addUserData.userRoleRules" prop="role">
				<el-select v-model="addUserData.submitProp.role" placeholder="请选择角色">
					<el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.name"> {{ item.name }}</el-option>
				</el-select>
			</el-form-item>
			<el-form-item v-if="addUserData.submitProp.role !== '机器人坐席'" label="姓名" :rules="addUserData.fullNameRules" prop="fullName">
				<el-input
					v-model="addUserData.submitProp.fullName"
					placeholder="请输入姓名"
					minlength="3"
					maxlength="16"
					oninput="value = value.replace(/[^a-zA-Z\u4e00-\u9fa5.\s]+$/g,'')"
					autocomplete="new-password"
				></el-input>
			</el-form-item>
			<!-- 若角色选择机器人，则密码和确认密码文本框隐藏 -->
			<!-- <el-form-item v-if="addUserData.submitProp.role !== '机器人坐席'" label="密码" :rules="addUserData.userPassRules" prop="pass">
				<el-input type="password" v-model="addUserData.submitProp.pass" placeholder="请输入密码" autocomplete="new-password" show-password></el-input>
			</el-form-item>
			<el-form-item v-if="addUserData.submitProp.role !== '机器人坐席'" label="确认密码" :rules="addUserData.userCheckPassRules" prop="checkPass">
				<el-input type="password" v-model="addUserData.submitProp.checkPass" placeholder="请再次输入密码" autocomplete="new-password" show-password></el-input>
			</el-form-item> -->
			<div class="btns">
				<el-button @click="cancel">取消</el-button>
				<el-button type="primary" @click="create">确认</el-button>
			</div>
		</el-form>
	</el-dialog>
</template>

<script>
import { mapState } from 'vuex';
import { createAccount } from '../../../api/api';
import { validatePass, validatePassChecked, validateUserName } from '@/utils/formValidate';
import FormReg from '@/utils/regexp';

export default {
	components: {},
	props: {
		show: {
			type: Boolean,
			default: false
		},
		roleList: {
			type: Array,
			default: () => []
		}
	},
	data() {
		var validateAgentName = (rule, value, callback) => {
			if (value.replace(FormReg.reg19, '').length !== 0) {
				callback(new Error('格式错误，姓名只能是英文或中文！'));
			} else if (value.trim() === '') {
				callback(new Error('“姓名为空！'));
			} else if (value.trim().length > 16 || value.trim().length < 2) {
				callback(new Error('格式错误，姓名长度为2-16位！'));
			} else {
				callback();
			}
		};
		return {
			fullNameReg: FormReg.reg9,
			addUserData: {
				submitProp: {
					userName: '',
					pass: '',
					checkpass: '',
					role: '',
					fullName: ''
				},
				userNameRules: [
					{ required: true, message: '用户名不能为空', trigger: ['blur', 'change'] },
					{ validator: validateUserName, trigger: 'blur' }
				],
				fullNameRules: [
					{ required: true, message: '姓名不能为空', trigger: ['blur', 'change'] },
					{ validator: validateAgentName, trigger: 'blur' }
				],
				userRoleRules: [{ required: true, message: '请选择角色', trigger: ['change'] }],
				userPassRules: [
					{ required: true, message: '请输入密码', trigger: ['blur', 'change'] },
					{ validator: validatePass, trigger: ['blur', 'change'] }
				],
				userCheckPassRules: [
					{ required: true, message: '请输入密码', trigger: ['blur', 'change'] },
					{ validator: validatePassChecked, trigger: ['blur', 'change'] }
				]
			},
			showDialog: false
		};
	},
	watch: {
		show(newVal) {
			this.showDialog = newVal;
			if (newVal) {
				this.$nextTick(() => {
					this.$refs['formRef'].clearValidate();
				});
			}
		}
	},
	computed: {
		...mapState({
			loginInfo: state => state.login.userInfo
		})
	},
	mounted() {},
	methods: {
		create() {
			this.$refs['formRef'].validate(valid => {
				if (valid) {
					this.createAgent(this.addUserData.submitProp);
				}
			});
		},
		cancel() {
			// this.$refs['formRef'].resetFields();
			this.reset();
			this.$emit('close');
		},
		createAgent(info) {
			const { userName, pass, role, fullName } = info;
			console.log('info', info, this.roleList);
			const roleItem = this.roleList.find(item => item.name === role);
			const isRobot = roleItem && roleItem.name === '机器人坐席';
			let data = {};
			data.userName = userName;
			data.org = this.loginInfo.org;
			data.role = role === '管理员' ? 'admin' : 'agent';
			data.pwd = isRobot ? 'zealcomm@ivcs_robot2021' : '111';
			data.isRobot = isRobot;
			data.fullName = fullName;
			data.profile = {
				isRobot: isRobot
			};
			data.roleId = roleItem.id;
			createAccount(data)
				.then(res => {
					if (res.status === 200) {
						this.$message.success('创建账号成功！');
						// this.$refs['formRef'].resetFields();
						this.reset();
						this.$emit('create');
					} else {
						this.$message.warning('创建账号失败');
					}
				})
				.catch(err => {
					this.$requestApiError(err, () => {
						this.$router.push('/');
					});
				});
		},
		reset() {
			this.addUserData.submitProp = {
				userName: '',
				pass: '',
				checkpass: '',
				role: ''
			};
		}
	}
};
</script>

<style lang="less">
.account {
	.btns {
		text-align: right;
	}
	.head {
		padding: 20px 0;
	}
	.el-avatar > img {
		width: 100%;
	}
}
</style>
